import { useState, useCallback } from 'react'
import { useNavigate, useLocation } from 'react-router-dom'
import { Menu, MenuProps } from 'antd'
import { useStore, observer } from '../../store'
import { useEnter } from '../../utils/hooks'
import LayoutMenuIcon from './LayoutMenuIcon'

function LayoutMenu (props: { onLoaded: (loaded: boolean) => void }) {
  const [menuList, setMenuList] = useState<MenuProps['items']>([])
  const { userStore } = useStore()
  const navigate = useNavigate()
  const location = useLocation()



  // 获取菜单列表和用户信息
  const fetchData = useCallback(async () => {
    // 菜单列表
    await userStore.getUserMenu()
    const deepMap = (source: UserStoreTypes.MenuItemProps[]): MenuProps['items'] => {
      return source.filter(menu => !menu.hide).map(menu => {
        const MenuIcon = menu.icon ? <LayoutMenuIcon icon={menu.icon} /> : <></>
        return {
          key: menu.url || menu.name,
          label: menu.label,
          title: menu.label,
          icon: MenuIcon,
          children: menu.children ? deepMap(menu.children) : null
        }
      })
    }
    // 用户信息
    await userStore.getUserInfo()
    setMenuList(deepMap(userStore.menuList))
    props.onLoaded(true)
  }, [props, userStore])

  // 初始化
  useEnter(() => {
    fetchData()
  })

  return (
    <Menu
      mode="inline"
      selectedKeys={[location.pathname]}
      className="layout-menu"
      items={menuList}
      onSelect={({ key }) => { navigate(key) }}
    />
  )
}

export default observer(LayoutMenu)
